package com.hvgroup.modules.sanic.web;

import com.hvgroup.modules.sanic.service.TaAssistantService;
import com.hvgroup.utils.SecurityUtils;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/ta")
@Api(tags = "测试助手api")
public class TaAssistantController {

    private final TaAssistantService taAssistantService;

    @PostMapping("/insert_demand_manager")
    public ResponseEntity<Object> insertDemandManager(@RequestBody Map<String, Object> requestBody, HttpServletRequest request) {
        Map<String, Object> formData = (Map<String, Object>) requestBody.get("project_data");
        String fileKey = (String) formData.get("file_key");
        String docName = (String) formData.get("doc_name");
        String docDesc = (String) formData.get("doc_desc");
        Long userId = SecurityUtils.getCurrentUserId();
        return ResponseEntity.ok(taAssistantService.insertDemandManagerToDb(userId, docName, docDesc, fileKey));
    }

    @PostMapping("/word_to_md")
    public ResponseEntity<Object> convertDocToMarkdown(@RequestBody Map<String, Object> body, HttpServletRequest request) {
        String fileKey = (String) body.get("file_key");
        Long userId = SecurityUtils.getCurrentUserId();
        return ResponseEntity.ok(taAssistantService.extractTocToMarkdown(userId, fileKey));
    }

    @PostMapping("/query_demand_records")
    public ResponseEntity<Object> queryDemandRecords(@RequestBody Map<String, Object> body, HttpServletRequest request) {
        int page = (int) body.getOrDefault("page", 1);
        int limit = (int) body.getOrDefault("limit", 10);
        String fileKey = (String) body.get("file_key");
        Long userId = SecurityUtils.getCurrentUserId();
        return ResponseEntity.ok(taAssistantService.queryDemandRecords(userId, fileKey, page, limit));
    }

    @PostMapping("/delete_demand_records")
    public ResponseEntity<Object> deleteDemandRecords(@RequestBody Map<String, Object> body) {
        Long id = Long.valueOf(String.valueOf(body.get("id")));
        return ResponseEntity.ok(taAssistantService.deleteDemandRecords(id));
    }

    @GetMapping(value = "/abstract_doc_func/{itemId}", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public ResponseBodyEmitter abstractDocFunc(@PathVariable("itemId") Long itemId) {
        ResponseBodyEmitter emitter = new ResponseBodyEmitter();
        taAssistantService.abstractDocFunc(emitter, itemId);
        return emitter;
    }

}
